package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {

    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprService empExprService;


    //分页查询
    @Override
    public PageResult<Emp> pageQuery(EmpQueryParam param) {
        //创建分页模型对象，获取初始页码和每页数量
        Page<Emp> page = Page.of(param.getPage(),param.getPageSize());

        //设置排序规则
        page.addOrder(OrderItem.desc("update_time"));

        //准备分页查询条件
        LambdaQueryWrapper<Emp> wrapper = new LambdaQueryWrapper<Emp>()
                .like(param.getName()!=null && !"".equals(param.getName()),Emp::getName,param.getName())
                        .eq(param.getGender()!=null,Emp::getGender,param.getGender())
                                .between(param.getBegin()!=null && param.getEnd()!=null,Emp::getEntryDate,param.getBegin(),param.getEnd());

        //调用Mybatis_plus的page方法
         page(page,wrapper);

         //获取所有的Emp对象
        List<Emp> emps = page.getRecords();

        //获取所有需要使用的部门ID
        Set<Integer> deptsID = emps.stream()
                                .map(Emp::getDeptId)
                                .collect(Collectors.toSet());


        List<Dept> depts = new ArrayList<>();
        //获取需要使用的部门信息
        if(!deptsID.isEmpty()) {
            depts = deptService.listByIds(deptsID);
        }
        //制作查询表格
        Map<Integer, String> deptMap = depts.stream()
                                     .collect(Collectors.toMap(Dept::getId,Dept::getName));

        //将信息填进Emp对象中
        for (Emp emp : emps) {
            emp.setDeptName(deptMap.get(emp.getDeptId()));
        }

         //返回需要返回的对象
         return new PageResult<Emp>(page.getTotal(),page.getRecords());

    }

    //新增员工
    @Transactional
    @Override
    public void saveEmp(Emp emp) {
        //1.保存员工基本信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        save(emp);
        //2.保存员工工作经历信息
        //获取工作经历
        List<EmpExpr> exprList = emp.getExprList();
        //添加id
        exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        empExprService.saveBatch(exprList);
    }

    //根据id查询员工信息
    @Override
    public Emp getEmpById(Integer id) {
        //1.查询员工信息
        Emp emp = getById(id);

        //2.查询员工经历
        LambdaQueryWrapper<EmpExpr> wrapper = new LambdaQueryWrapper<EmpExpr>()
                .eq(EmpExpr::getEmpId, id );

        List<EmpExpr> exprList = empExprService.list(wrapper);
        emp.setExprList(exprList);

        return emp;
    }

    //执行修改
    @Override
    @Transactional
    public void updateEmp(Emp emp) {
        //1.修改员工信息
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);
        //2.修改员工经历
        //(1).删除原有经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId,emp.getId()));

        //(2).添加新增经历
        List<EmpExpr> exprList = emp.getExprList();
        if(exprList!=null && !exprList.isEmpty()){
            //填充id
            exprList.forEach(expr ->expr.setEmpId(emp.getId()));
        }
        empExprService.saveBatch(exprList);

    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        if(ids == null || ids.isEmpty()){
            return;
        }
        //1.删除员工
        removeBatchByIds(ids);
        //2.删除员工经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids));
    }

}

